package sync;
/*
synchronized模拟卖票
 */
//第一步创建资源类，定义属性和操作方法
class Ticket{

//  属性：票数
  private int count = 30;
//  操作方法：卖票
  public synchronized void sale(){
//  判断是否有票
    if(count > 0){
//  打印出谁卖了票
      System.out.println(Thread.currentThread().getName() + "卖了：" + (count--) + " 剩下：" + count);
    }
  }
}


//第二步：创建三个线程,分别叫做AA,BB,CC，并且调用40次卖票
public class SaleTicket {

  public static void main(String[] args) {

    Ticket ticket = new Ticket();

    new Thread(new Runnable() {
      @Override
      public void run() {
        for(int i = 0; i < 40; i++){
          ticket.sale();
        }
      }
    },"AA").start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        for(int i = 0; i < 40; i++){
          ticket.sale();
        }
      }
    },"BB").start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        for(int i = 0; i < 40; i++){
          ticket.sale();
        }
      }
    },"CC").start();
  }
}
